package cn.wei.youvierpc.protocol;

import cn.wei.youvierpc.serializer.Serializer;
import cn.wei.youvierpc.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;

public class ProtocolMessageEncoder {

    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException {
        if (protocolMessage == null || protocolMessage.getHeader() == null) {
            return Buffer.buffer();
        }

        ProtocolMessage.Header header = protocolMessage.getHeader();

        Buffer buffer = Buffer.buffer();
        buffer.appendByte(header.getMagic())
                .appendByte(header.getVersion())
                .appendByte(header.getSerializer())
                .appendByte(header.getType())
                .appendByte(header.getStatus())
                .appendLong(header.getRequestId());

        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByKey(header.getSerializer());

        if (serializerEnum == null) {
            throw new RuntimeException(" 序列化器不存在");
        }
        Serializer serializer = SerializerFactory.getInstance(serializerEnum.getValue());

        byte[] bodyData = serializer.serialize(protocolMessage.getBody());
        buffer.appendInt(bodyData.length)
                .appendBytes(bodyData);

        return buffer;
    }
}
